﻿#define _CRT_SECURE_NO_WARNINGS 1
#include "Link.h"
//创建节点
Link* BuyNode(int x) {
	Link* newnode = (Link*)malloc(sizeof(Link));
	if (newnode == NULL) {
		perror("malloc Faill!");
		exit(1);
	}
	else {
		newnode->val = x;
		newnode->next = newnode->prev = newnode;
	}
	return newnode;
}
//链表打印
void LTprint(Link* phead) {
	if (phead) {
		Link* pcur = phead->next;
		while (pcur != phead) {
			printf("%d->", pcur->val);
			pcur = pcur->next;
		}
		printf("\n");
	}
	else
		printf("NULL\n");
}
//链表初始化
Link* LTInit(Link** pphead) {
	//创建哨兵位
	Link* newnode = BuyNode(-1);
	*pphead = newnode;
}
//链表尾插
Link* LTPushBack(Link* phead, LinkDate x) {
	assert(phead);
	Link* newnode = BuyNode(x);
	newnode->prev = phead->prev;
	newnode->next = phead;
	phead->prev = newnode;
	phead->next->next = newnode;
}
//链表头插
void LTPushFront(Link* phead, LinkDate x) {
	assert(phead);
	Link* newnode = BuyNode(x);
	newnode->next = phead->next;
	newnode->prev = phead;
	phead->next->prev = newnode;
	phead->next = newnode;
}
//链表尾删
void LTPopBack(Link* phead) {
	assert(phead && phead->next != phead);
	Link* del = phead->prev;
	del->prev->next = phead;
	phead->prev = del->prev;
	free(del);
	del = NULL;
}
//链表头删
void LTPopFront(Link* phead) {
	assert(phead && phead->next != phead);
	Link* del = phead->next;
	phead->next = del->next;
	del->next = phead;
}
//链表查找
Link* LTFind(Link* phead, LinkDate x) {
	assert(phead && phead->next != phead);
	Link* pcur = phead->next;
	while (pcur != phead) {
		if (pcur->val == x) {
			return pcur;
		}
		pcur = pcur->next;
	}
	return NULL;
}
//在pos位置之后插⼊数据 
void LTInsert(Link* pos, LinkDate x) {
	assert(pos);
	Link* newnode = BuyNode(x);
	newnode->next = pos->next;
	newnode->prev = pos;
	pos->next->prev = newnode;
	pos->next = newnode;
}
//在pos删除数据 
void LTErase(Link* pos) {
	assert(pos);
	pos->next->prev = pos->next;
	pos->prev->next = pos->next;
	free(pos);
	pos = NULL;
}
//链表销毁(先存再删)
void LTDestroy(Link* phead)
{
	Link* pcur = phead->next;
	while (pcur != phead) {
		Link* next = pcur->next;
		free(pcur);
		pcur = next;
	}
	free(phead);
	phead = NULL;
}